package com.bjy.qa.service.ssh.impl;

import com.bjy.qa.entity.ssh.Results;
import com.bjy.qa.entity.ssh.SSHServer;
import com.bjy.qa.service.ssh.ISSHService;
import com.jcraft.jsch.JSchException;
import com.rslai.commons.ssh.Jsch;
import com.rslai.commons.ssh.SSH;
import com.rslai.commons.ssh.SSHConfig;
import com.rslai.commons.ssh.SSHResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeoutException;

@Service
public class SSHService implements ISSHService {

    @Override
    public List<Results> executeCmd(SSHServer sshServer) throws JSchException, IOException, TimeoutException {
        SSHConfig sshConfig = new SSHConfig();
        sshConfig.setHost(sshServer.getHost()); // ssh 服务器地址
        sshConfig.setUsername(sshServer.getUserName()); // 登录 ssh 用户名
        sshConfig.setPassword(sshServer.getPassword()); // 登录 ssh 密码
        sshConfig.setPort(sshServer.getPort());
        sshConfig.setJumpServer(sshServer.isJumpServer()); // 如果连接的是 JumpServer 要设置true

        List<Results> sshResponseList = new LinkedList<Results>();
        SSH ssh;
        ssh = new Jsch(sshConfig);

        for (String cmd : sshServer.getCmdList()) {
            Results results = new Results();
            try {
                SSHResponse sshResponse = ssh.execute(cmd);
                results.setCmd(sshResponse.getCmd());
                results.setBody(sshResponse.getBody());
                results.setPrompt(sshResponse.getPrompt());
                results.setStatus(true);
            } catch (Exception e) {
                results.setCmd(cmd);
                results.setStatus(false);
                results.setBody(e.getMessage());
            }
            sshResponseList.add(results);
        }

        try {
            ssh.disconnect(); // 释放ssh链接
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return sshResponseList;
    }

}
